<template>
  <a-drawer :open="visible" title="司机回库详情" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <template #extra>
      <a-space :size="5">
        <span>{{ options?.return_no }}</span>
        <span>司机:{{ options?.driver?.name }}</span>
        <span>{{ options?.create_time }}</span>
        <!-- <a-button type="link" @click="changeLogModal(true)">查看日志</a-button> -->
        <a-button @click="print">
          <template #icon>
            <PrinterOutlined />
          </template>
          打印({{ orderLog?.print_count ?? 0 }})
        </a-button>
      </a-space>
    </template>
    <a-card size="small" title="回库基本信息" style="margin-bottom: 20px">
      <a-descriptions size="small" :column="3">
        <a-descriptions-item label="回库单号">
          <CopyText :text="options?.return_no" />
        </a-descriptions-item>
        <a-descriptions-item label="订单数量">{{ options?.order_count }}</a-descriptions-item>

        <a-descriptions-item label="司机">{{ options?.driver?.name }}</a-descriptions-item>

        <a-descriptions-item label="出库仓库"> {{ options?.driverWarehouse?.name }}({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', options?.driverWarehouse?.attribute_type) }} )</a-descriptions-item>
        <a-descriptions-item label="回库仓库"> {{ options?.intoWarehouse?.name }}({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', options?.intoWarehouse?.attribute_type) }} )</a-descriptions-item>
        <a-descriptions-item label="回库类型">
          <span>{{ getDescByValue('RETURNWAREHOUSE_TYPE_ENUM', options?.return_type) }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="回库状态">
          <span>{{ getDescByValue('RETURNWAREHOUSE_STATUS_ENUM', options?.return_status) }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="回库数量">{{ options?.order_large_qty }}整{{ options?.order_middle_qty }}中{{ options?.order_small_qty }}散</a-descriptions-item>
        <a-descriptions-item label="回库货值">{{ options?.order_amount }}</a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card size="small" title="回库签收信息" style="margin-bottom: 20px">
      <a-descriptions size="small" :column="3">
        <a-descriptions-item label="签收状态">
          <span>{{ getDescByValue('RETURNWAREHOUSE_STATUS_ENUM', options?.return_status) }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="签收数量">{{ options?.sign_large_qty }}整{{ options?.sign_middle_qty }}中{{ options?.sign_small_qty }}散</a-descriptions-item>
        <a-descriptions-item label="签收商品货值">{{ options?.sign_amount }}</a-descriptions-item>
        <a-descriptions-item label="签收人">{{ options?.companyUser?.username }}</a-descriptions-item>
        <a-descriptions-item label="签收日期">{{ options?.sign_time }}</a-descriptions-item>
        <a-descriptions-item label="签收备注">{{ options?.sign_remark }}</a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card style="width: 100%" :tab-list="tabListNoTitle" :active-tab-key="noTitleKey" @tabChange="(key) => onTabChange(key, 'noTitleKey')">
      <div v-if="noTitleKey === 'order'">
        <a-table :dataSource="dataList" :columns="columnsOrder" :pagination="false" :scroll="{ x: 'max-content' }" rowKey="id" size="small" bordered :showExpandColumn="false" expandRowByClick>
          <template #bodyCell="{ text, record, column }">
            <template v-if="column.dataIndex === 'order_no'">
              <CopyText :text="text">
                <a @click="detail(record)">{{ text + ' ' }} </a>
              </CopyText>
            </template>
            <template v-if="column.dataIndex === 'order_num'"> {{ record?.order_qty_whole }}整{{ record?.order_qty_medium }}中{{ record?.order_qty_scattered }}散 </template>
            <template v-if="column.dataIndex === 'return_num'"> {{ record?.return_qty_whole }}整{{ record?.return_qty_medium }}中{{ record?.return_qty_scattered }}散 </template>
            <template v-if="column.dataIndex === 'sign_num'"> {{ record?.into_receivable_qty_whole }}整{{ record?.into_receivable_qty_medium }}中{{ record?.into_receivable_qty_scattered }}散 </template>
          </template>
        </a-table></div
      >
      <div v-else-if="noTitleKey === 'goods'">
        <a-table :dataSource="goodsList" :columns="columns" :pagination="false" :scroll="{ x: 'max-content' }" rowKey="goods_id" size="small" bordered :showExpandColumn="false" expandRowByClick>
          <template #bodyCell="{ text, record, column }">
            <template v-if="column.dataIndex === 'goods_name'">
              <CopyText :text="text">
                {{ text }}
              </CopyText>
            </template>
            <template v-if="column.dataIndex === 'return_num'"> {{ record?.return_qty_whole }}{{ record?.return_qty_medium }}{{ record?.return_qty_scattered }} </template>
            <template v-if="column.dataIndex === 'sign_num'"> {{ record?.sign_qty_whole }}{{ record?.sign_qty_medium }}{{ record?.sign_qty_scattered }} </template>
          </template>
          <template #expandedRowRender="{ record }">
            <div class="content">
              <div class="parent" v-for="item in record.batches" :key="item.code">
                <div class="div1">批次：{{ dayjs(item?.batch_time).format('YYYY-MM-DD') }}</div>
                <div class="div2">数量：{{ transformSpec(item?.quantity, record?.specs) }}</div>
                <div class="div3">仓库：{{ item?.warehouse_name }}</div>
                <div class="div3">库位：{{ item?.code }}</div>
              </div>
            </div>
          </template>
        </a-table></div
      >
    </a-card>
    <LogModal v-model:open="showLogModal" @close="changeLogModal(false)" :tableData="orderLog" />
    <PurchaseReceiptPrintModal ref="printRef" />
    <SalesDetailsModal ref="detailRef" />
    <template #footer>
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import _ from 'lodash'
import { message } from 'ant-design-vue'
import SalesDetailsModal from './sales-details-modal.vue'
import { salesApi } from '@/api/business/sale/sales-api'
import { useEnums } from '@/hooks/plugins/useEnums'
import { driverReturnOrderApi } from '@/api/business/storage/returnwarehouse-api'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import PurchaseReceiptPrintModal from './return-receipt-print-modal.vue'
import { useTransformSpec } from '@/hooks/web/use-transform-spec'
const loadingStore = useLoadingStore()
const { getDescByValue } = useEnums()
const { transformSpec } = useTransformSpec()
defineExpose({
  showDrawer
})
const emit = defineEmits(['reload-list'])

// --------------------- Drawer 显示与隐藏 ---------------------
// 是否展示
const visible = ref(false)
// 详情
const options = ref<any>()

function showDrawer(item) {
  // options.value = item
  singleDetail(item)
  visible.value = true
}

const onClose = () => {
  dataList.value = []
  visible.value = false
}
// 切换标签
const tabListNoTitle = [
  {
    key: 'order',
    tab: '订单明细'
  },
  {
    key: 'goods',
    tab: '商品明细'
  }
]
const noTitleKey = ref('order')
const onTabChange = (value: string, type: string) => {
  if (type === 'noTitleKey') {
    noTitleKey.value = value
  }
}
// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = async (rowData) => {
  try {
    const res: any = await salesApi.detail({ id: rowData.order_id })
    detailRef.value.showDrawer(res.data)
  } catch (e: any) {
    message.error(e.msg)
    errorSentry.captureError(e)
  }
}
// --------------------- 入库商品 ---------------------
const dataList = ref<any[]>([])
const orderLog = ref([])
const goodsList = ref({})
const columns = reactive([
  {
    title: '商品名称',
    dataIndex: 'goods_name'
  },
  {
    title: '规格',
    dataIndex: 'spec_name'
  },
  {
    title: '单位',
    dataIndex: 'unit'
  },
  {
    title: '应回库数量',
    dataIndex: 'return_num'
  },
  {
    title: '应回库金额',
    dataIndex: 'return_amount'
  },
  {
    title: '仓库签收数量',
    dataIndex: 'sign_num'
  },
  {
    title: '仓库签收金额',
    dataIndex: 'sign_amount'
  },
  {
    title: '备注',
    dataIndex: 'goods_remark'
  }
])
// 订单
const columnsOrder = reactive([
  {
    title: '订单编号',
    dataIndex: 'order_no'
  },
  {
    title: '门店名称',
    dataIndex: 'store_name'
  },
  {
    title: '订单类型',
    dataIndex: 'order_type_text'
  },
  {
    title: '订单数量',
    dataIndex: 'order_num'
  },
  {
    title: '订单金额',
    dataIndex: 'order_amount'
  },
  {
    title: '应回库数量',
    dataIndex: 'return_num'
  },
  {
    title: '应回库金额',
    dataIndex: 'return_amount'
  },
  {
    title: '仓库签收数量',
    dataIndex: 'sign_num'
  },
  {
    title: '仓库签收金额',
    dataIndex: 'into_receivable_amount'
  },
  {
    title: '备注',
    dataIndex: 'order_remark'
  }
])

// 聚合同批次、库位的库存批次数据并换算成可读格式
const formatInventoryBatches = (inventoryBatches: any[]) => {
  const list = new Map()
  for (const item of inventoryBatches) {
    if (item.quantity === 0) continue
    const time = dayjs(item.batch_time).format('YYYY-MM-DD').valueOf()
    const key = `${time}${item?.warehouse_location_id ? `-${item.warehouse_location_id}` : ''}`
    // 将仓库位置的code数组转换为逗号分隔的字符串
    const locationCodes = item.location ? item?.location.map((location: any) => location?.code).join('| ') : ''
    const value = {
      batch_time: time,
      code: locationCodes,
      // code: `${item.location?.code ?? '-'}`,
      warehouse_name: `${item?.warehouse?.name}(${getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item?.warehouse?.attribute_type)})`,
      quantity: item.quantity
    }
    if (list.has(key)) {
      const temp = list.get(key)
      temp.quantity += value.quantity

      // 合并code
      const existingCodes = temp.code.split(', ').map((code) => code.trim())
      const newCodes = value.code.split(', ').map((code) => code.trim())
      const combinedCodes = [...new Set([...existingCodes, ...newCodes])].join(', ') // 去重并合并
      temp.code = combinedCodes

      list.set(key, temp)
    } else {
      list.set(key, value)
    }
  }
  return Array.from(list.values()).sort((a, b) => b.batch_time - a.batch_time)
}
// 详情
async function singleDetail(rowData) {
  try {
    loadingStore.show()
    const res: any = await driverReturnOrderApi.driverReturnOrderOrder({ id: rowData.id, is_sign_detail: 0 })
    options.value = res.data.row
    dataList.value = res.data.orderGroup
    orderLog.value = res.data.printLog
    goodsList.value = res.data.goodsGroup.map((item) => {
      return {
        ...item,
        batches: item.goods_batches ? formatInventoryBatches(item.goods_batches) : []
      }
    })
  } catch (e: any) {
    if (e.msg) {
      message.error(e.msg)
    }
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}

const showLogModal = ref(false)
function changeLogModal(status: boolean) {
  showLogModal.value = status
}
</script>
<style lang="less" scoped>
:deep(.ant-table-expanded-row .ant-table-cell) {
  background-color: #e6f4ff;
}
:deep(.ant-table-expanded-row .ant-table-cell:hover) {
  background-color: #e6f4ff;
}
.content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.parent {
  // margin-left: 45%;
  // margin-right: 5%;
  display: grid;
  grid-template-columns: 30% 30% 20% 20%;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.parent:last-of-type {
  border-bottom: none;
}

.div3 {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本 */
  width: 100%; /* 设置一个宽度限制，以便文本超出时能看到效果 */
}
:deep(.ant-tabs-tab) {
  font-size: 14px !important;
  font-weight: 600;
}
:deep(.ant-tabs-nav) {
  height: 54px;
  font-size: 14px;
  font-weight: 600;
}
</style>
